#pragma once
#include<iostream>
#include<string>
#include<mutex>
#include<stdlib.h>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include"log.hpp"


using namespace std;
//using std::cout;
//using std::endl;
//using std::cin;

#define BACKLOG 5
//单列模式
class TcpServer
{
    private:
    TcpServer(int port)
        :_port(port),_listen_sock(-1)
    {}
    TcpServer(const TcpServer& T) = delete;
    void operator=(const TcpServer& T) = delete;
    public:
    static TcpServer* getTcpserver(int port)
    {
        static mutex mtx;
        if(_tcpser == nullptr)
        {
            mtx.lock();
            if(_tcpser == nullptr)
            {
                _tcpser = new TcpServer(port);
                _tcpser->Init();
            }
            mtx.unlock();
        }
        return _tcpser;
    }
    void Init()
    {
        Socket();
        Bind();
        Listen();
        LOG(INFP,"Tcp success ");
    }
    void Socket()
    {
        _listen_sock = socket(AF_INET,SOCK_STREAM,0);
        if(_listen_sock < 0)
        {
            LOG(FATAL,"sock error (sock套接字创建失败)");
            exit(2);
        }
        int opt = 1;
        setsockopt(_listen_sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
        LOG(INFO,"sock success");
    }
    int retsock()
    {
        return _listen_sock;
    }

    void Bind()
    {
        sockaddr_in locae;
        memset(&locae,0,sizeof(locae));
        locae.sin_family = AF_INET;
        locae.sin_port = htons(_port);
        locae.sin_addr.s_addr = INADDR_ANY;
        if(bind(_listen_sock,(sockaddr*)&locae,sizeof(locae)) < 0)
        {
            LOG(FATAL,"port bind error (端口绑定失败)");
            exit(3);
        }
        LOG(INFO,"port success 绑定成功");
    }
    void Listen()
    {

        if(listen(_listen_sock,BACKLOG) < 0)
        {
            LOG(FATAL,"listen sock error (监听失败)");
            exit(4);
        }
        LOG(INFO,"listen success 启动监听");
    }
    ~TcpServer()
    {
        if(_listen_sock >= 0) close(_listen_sock);
    }
    private:
    int _port;
    int _listen_sock;
    static TcpServer* _tcpser;
};

TcpServer* TcpServer::_tcpser = nullptr;
